import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Collapse} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION, claimApplyStatusSale} from './constants';
import {repairType, dealerType, isKd, faultType, isYesNo, claimApplyStatus} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import TagSelect from 'Shared/components/TagSelect';
import SearchSelect from 'Shared/components/SearchSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import FaultItemSelectPanel from './PageAdd/FaultItemSelectPanel';
import MultipleSelect from '../common/MultipleSelect';
import Export from '../common/Export';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import routes from './routes';
import {faultItemQuickly} from './api';
import styles from './style.css';
const FormItem = Form.Item;
const {Panel} = Collapse;

const repairTypeList = repairType.toList(language);
const isKdList = isKd.toList(language);
const faultTypeList = faultType.toList(language);
const isYesNoList = isYesNo.toList(language);
const dealerConditions = {
    type: dealerType.总代
};
class QueryPanel extends React.PureComponent {
    state = {
        showFaultItem: false,
    }
    componentDidMount() {
        this.props.initSearch();
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearch();
    }
    labelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }
    onSelectDealer = data => {
        this.props.onConditionsChange('dealerId', data.id);
        this.props.onQueryDealerChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    onSearchFaultItem = value =>
        faultItemQuickly({
            query: value
        })
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            });
    onSelectFaultItem = data => {
        this.props.onConditionsChange('faultItemId', data.id);
        this.props.onQueryFaultItemChange({
            id: data.id,
            code: data.code,
            name: data.name,
        });
        this.setState({
            showFaultItem: false
        });
    }
    onClickFaultItem = () => {
        this.setState({showFaultItem: true});
    }
    onCloseFaultItem = () => {
        this.setState({showFaultItem: false});
    }
    onClickStopPropagation = e => {
        e.stopPropagation();
    }
    render() {
        const operations = [];
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.queryDealer.id,
            code: this.props.queryDealer.code,
            name: this.props.queryDealer.name
        } : null;
        const faultItemInfo = this.props.conditions.faultItemId ? {
            id: this.props.queryFaultItem.id,
            code: this.props.queryFaultItem.code,
            name: this.props.queryFaultItem.name
        } : null;
        if(hasPermissions(this.props.permissions, PERMISSION.historySearch))
            operations.push(<Button key="historySearch" href={`#${routes.historyQuery.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.historySearch',
                defaultMessage: '历史查询'
            })}</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.add))
            operations.push(<Button key="add" type="primary" href={`#${routes.add.url()}`}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.add',
                defaultMessage: '新增'
            })}</Button>);
        return (
            <div className={styles.collapse}>
                <Collapse>
                    <Panel key="1" header={<Row>
                        <Col span={2} className={styles.titleName}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.form.common',
                                defaultMessage: '基础信息'
                            })}
                        </Col>
                        <Col span={22}>
                            <Row>
                                <Form className="form-standard">
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.brandId',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <div onClick={this.onClickStopPropagation}><WrappedSelect
                                                allowClear
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.initEnum.brands}
                                                onChange={this.handleFilterChange} /></div>
                                        </FormItem>
                                    </Col>
                                    
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.code',
                                                defaultMessage: '预授权单号'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <div onClick={this.onClickStopPropagation}><TextInput
                                                name="code"
                                                value={this.props.conditions.code}
                                                onPressEnter={this.handleFilterPressEnter}
                                                onBlur={this.handleFilterChange} /></div>
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                        </Col>
                    </Row>}>
                        <Form className="form-standard">
                            <Row>
                                {!this.props.isDealerUser &&
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <DealerSelectPanel
                                                conditions={dealerConditions}
                                                value={dealerInfo}
                                                onSelect={this.onSelectDealer} />
                                        </FormItem>
                                    </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.subDealerCode',
                                            defaultMessage: '经销商编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="subDealerCode"
                                            value={this.props.conditions.subDealerCode}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.subClaimApplyCode',
                                            defaultMessage: '经销商申请单号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="subClaimApplyCode"
                                            value={this.props.conditions.subClaimApplyCode}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem class={styles.multiLabel}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.repairCode',
                                            defaultMessage: '维修单号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="repairCode"
                                            value={this.props.conditions.repairCode}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.repairType',
                                            defaultMessage: '索赔类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="repairType"
                                            value={this.props.conditions.repairType}
                                            options={repairTypeList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.faultItemId',
                                            defaultMessage: '故障代码'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <SearchSelect
                                            allowClear
                                            value={faultItemInfo}
                                            placeholder={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.faultItem.placeholder',
                                                defaultMessage: '请输入故障代码名称或编号进行查询'
                                            })}
                                            onSelect={this.onSelectFaultItem}
                                            onSearch={this.onSearchFaultItem}
                                            keyIndex="id"
                                            labelMap={this.labelMap}
                                            onClickSearchBtn={this.onClickFaultItem} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.isCountersign',
                                            defaultMessage: '是否会签'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="isCountersign"
                                            value={this.props.conditions.isCountersign}
                                            options={isYesNoList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.approverName',
                                            defaultMessage: '审核人'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="approverName"
                                            value={this.props.conditions.approverName}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.faultType',
                                        defaultMessage: '故障类型'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TagSelect
                                            name="faultType"
                                            value={this.props.conditions.faultType}
                                            options={faultTypeList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.status',
                                        defaultMessage: '状态'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TagSelect
                                            name="status"
                                            value={this.props.conditions.status}
                                            options={this.props.isDealerUser ? claimApplyStatusSale.toList(language) : claimApplyStatus.toList(language)}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Panel>
                    <Panel key="2" header={<Row>
                        <Col span={2} className={styles.titleName}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.form.vehicle',
                                defaultMessage: '车辆信息'
                            })}
                        </Col>
                        <Col span={22}>
                            <Row>
                                <Form className="form-standard">
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.vin',
                                                defaultMessage: 'VIN'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <div onClick={this.onClickStopPropagation}><TextInput
                                                name="vin"
                                                value={this.props.conditions.vin}
                                                onPressEnter={this.handleFilterPressEnter}
                                                onBlur={this.handleFilterChange} /></div>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.productCategoryCode',
                                                defaultMessage: '车型编号'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <div onClick={this.onClickStopPropagation}><MultipleSelect
                                                name="productCategoryCode"
                                                dataOptions={this.props.categories}
                                                value={this.props.conditions.productCategoryCode}
                                                onBlur={this.handleFilterChange} /></div>
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                        </Col>
                    </Row>}>
                        <Form className="form-standard">
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.engineCode',
                                            defaultMessage: '发动机号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="engineCode"
                                            value={this.props.conditions.engineCode}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.transmissionSn',
                                            defaultMessage: '变速箱号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="transmissionSn"
                                            value={this.props.conditions.transmissionSn}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.isKd',
                                            defaultMessage: 'CBU/KD'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="isKd"
                                            value={this.props.conditions.isKd}
                                            options={isKdList}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Panel>
                    <Panel key="3" disabled={true} header={<Row>
                        <Col span={2} className={styles.titleName}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.form.part',
                                defaultMessage: '备件信息'
                            })}
                        </Col>
                        <Col span={22}>
                            <Row>
                                <Form className="form-standard">
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.causePartCode',
                                                defaultMessage: '主损件编号'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput
                                                name="causePartCode"
                                                value={this.props.conditions.causePartCode}
                                                onPressEnter={this.handleFilterPressEnter}
                                                onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.causePartName',
                                                defaultMessage: '主损件名称'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <TextInput
                                                name="causePartName"
                                                value={this.props.conditions.causePartName}
                                                onPressEnter={this.handleFilterPressEnter}
                                                onBlur={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                        </Col>
                    </Row>} />
                    <Panel key="4" disabled={true} header={<Row>
                        <Col span={2} className={styles.titleName}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.form.datatime',
                                defaultMessage: '时间信息'
                            })}
                        </Col>
                        <Col span={22}>
                            <Row>
                                <Form className="form-standard">
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.submitTime',
                                                defaultMessage: '提交时间'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <DateRangePicker name="submitTime" value={this.props.conditions.submitTime}
                                                onChange={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.approveTime',
                                                defaultMessage: '审核时间'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <DateRangePicker name="approveTime" value={this.props.conditions.approveTime}
                                                onChange={this.handleFilterChange} />
                                        </FormItem>
                                    </Col>
                                </Form>
                            </Row>
                        </Col>
                    </Row>} />
                </Collapse>
                <Form className={styles.fromtop}>
                    <Row>
                        <Col span={6} className={styles['inline-button']}>
                            <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button key="clear" onClick={this.props.onResetClick}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            {hasPermissions(this.props.permissions, PERMISSION.queryExport) &&
                                <Export key={PERMISSION.queryExport} exportButton={this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.exportButton',
                                    defaultMessage: '查询导出'
                                })} exportRequest={this.props.onClickExport} />}
                            {operations}
                        </Col>
                    </Row>
                    {
                        this.state.showFaultItem &&
                        <FaultItemSelectPanel
                            selectKey={this.props.queryFaultItem.id}
                            onCancel={this.onCloseFaultItem}
                            onSelect={this.onSelectFaultItem} />
                    }
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    initEnum: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onQueryDealerChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    categories: PropTypes.array,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    queryDealer: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    saveQueryDealer,
    exportData,
    saveQueryFaultItem,
    initSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);

const getCategoryData = createSelector(
    state => state.getIn(['page', 'domainData', 'category']),
    init => {
        const initData = init.toJS();
        const categories = initData.data ? initData.data.map(item => ({
            code: item.code
        })) : [];
        return categories;
    }
);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getQueryFaultItem = selectorFactory(['page', 'appState', 'queryFaultItem']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getInitData(state),
    conditions: getConditions(state),
    queryDealer: getQueryDealer(state),
    permissions: getPermissions(state),
    queryFaultItem: getQueryFaultItem(state),
    categories: getCategoryData(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onQueryDealerChange: data => dispatch(saveQueryDealer(data)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData()),
    onQueryFaultItemChange: data => dispatch(saveQueryFaultItem(data)),
    initSearch: () => dispatch(initSearch()),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
